package com.kldy8.kldyw.filmfactory.company;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import com.andview.refreshview.XRefreshView;
import com.kldy8.kldyw.R;
import com.kldy8.kldyw.filmfactory.bean.City;
import com.kldy8.kldyw.filmfactory.bean.Company;
import com.kldy8.kldyw.filmfactory.bean.Positions;
import com.kldy8.kldyw.logre.LoginActivity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.tools.widget.view.ExpandTabView;
import com.kldy8.kldyw.tools.widget.view.ViewLeft;
import com.kldy8.kldyw.tools.widget.view.ViewMiddle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;

/**
 *  * 经纪公司   Film and television company   制作公司  宣发公司
 */
public class CompanyActivity extends AppCompatActivity
{
    private List<Positions> positionsList1 = new ArrayList<Positions>();
    private List<City> cityList1 = new ArrayList<City>();

    int page1 = 1;
    int position1,city1;

    private LayoutInflater mInflater;
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合

    private CompanyAdapter adapter1;

    private TabLayout mTabLayout;
    private Toolbar toolbar;

    private XRefreshView  refreshView;

    //公司类型
    String typeid;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company);

        Intent intent = getIntent();
        String title = "";
        typeid = intent.getStringExtra("type_id");
        Log.e("type_id",typeid);

        if (typeid.equals("15"))
        {
            title = getResources().getString(R.string.jj_com);
        }
        if (typeid.equals("14"))
        {
            title = getResources().getString(R.string.flim_com);

        }
        if (typeid.equals("16"))
        {
            title = getResources().getString(R.string.make_com);

        }
        if (typeid.equals("17"))
        {
            title = getResources().getString(R.string.xf_com);
        }

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(title);//设置主标题
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true); // 决定左上角图标的右侧是否有向左的小箭头, true
        // 有小箭头，并且图标可以点击
        actionBar.setDisplayShowHomeEnabled(false);

        mTabLayout = (TabLayout) findViewById(R.id.tabs);
//        spinner1 = (Spinner) findViewById(R.id.spinner1);
//        spinner2 = (Spinner) findViewById(R.id.spinner2);

        initViewPage();
        initListView();
        initData(""+typeid);
    }

    private void initData(String type_id)
    {
        initCompanyFilter();
        initCompanyList(true,""+1,type_id);
    }

    private void initCompanyFilter()
    {
        ServerApi.company_filter(new ServerCallBack() {
            @Override
            public void onError(Request request, Exception e)
            {

            }

            @Override
            public void onResponse(String response) throws JSONException
            {
                JSONObject jsonObject = new JSONObject(response);
                if ("0".equals(jsonObject.optString("code")))
                {
                    Log.e("......",response.toString());
                    if ("0".equals(jsonObject.optString("code")))
                    {
                        JSONObject objectData = jsonObject.optJSONObject("data");
                        JSONArray type_ids = objectData.optJSONArray("type_ids");
                        JSONArray cities = objectData.optJSONArray("cities");

                        if (null != type_ids && type_ids.length()>0)
                        {
                            for (int i = 0; i < type_ids.length(); i++) {
                                JSONObject object = type_ids.optJSONObject(i);
                                Positions ids = Positions.resolution(object);
                                if (ids != null)
                                {
                                    positionsList1.add(ids);
                                }
                            }
                        }


                        if (null != cities && cities.length()>0)
                        {
                            for (int i = 0; i < cities.length(); i++) {
                                JSONObject object = cities.optJSONObject(i);
                                City city = new City();
                                if (city != null)
                                {
                                    cityList1.add(city);
                                }
                            }
                        }

                        initExpandView(1,positionsList1,cityList1);
                        initExpandVaule(1);
                        initExpandListener(1);
                    }
                }
                else  if ("10004".equals(jsonObject.optString("code")))
                {
                    Intent intent2 = new Intent();
                    intent2.setClass(CompanyActivity.this, LoginActivity.class);
                    startActivity(intent2);
                    CompanyActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                }


            }
        });
    }

    private void initCompanyList(final boolean isInit, String page, String type_id )
    {

        ServerApi.company_list(page, type_id, new ServerCallBack()
        {
            @Override
            public void onError(Request request, Exception e)
            {
                if (refreshView!=null)
                {
                    refreshView.stopRefresh();
                    refreshView.stopLoadMore();
                }
            }

            @Override
            public void onResponse(String response) throws JSONException
            {
                Log.e("......",response.toString());
                Log.e("page1",""+page1);

                ArrayList<Company> company1 = new ArrayList<Company>();

                JSONObject jsonObject = new JSONObject(response);
                if ("0".equals(jsonObject.optString("code")))
                {
                    page1++;
                    JSONObject objectData = jsonObject.optJSONObject("data");
                    JSONArray objectList = objectData.optJSONArray("list");

                    if (isInit == true)
                    {
                        page1 = 2;
                    }

                    if (null != objectList && objectList.length()>0)
                    {
                        for (int i = 0; i < objectList.length(); i++) {
                            JSONObject object = objectList.optJSONObject(i);
                            Company company = Company.resolution(object);

                            if (company != null)
                            {
                                company1.add(company);
                            }
                        }
                    }
                    adapter1.replaceOrAdd(isInit,company1);
                    adapter1.notifyDataSetChanged();
                }
                else  if ("10004".equals(jsonObject.optString("code")))
                {
                    Intent intent2 = new Intent();
                    intent2.setClass(CompanyActivity.this, LoginActivity.class);
                    startActivity(intent2);
                    CompanyActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                }

                if (refreshView!=null)
                {
                    refreshView.stopRefresh();
                    refreshView.stopLoadMore();
                }
            }
        });
    }



   ListView list_view;

    private void initListView() {
        list_view = (ListView) findViewById(R.id.list_view);
        adapter1 = new CompanyAdapter(this, new ArrayList<Company>(), 0);
        list_view.setAdapter(adapter1);

        refreshView = (XRefreshView) findViewById(R.id.xrefreshview);

        refreshView.setPullLoadEnable(true);
        //设置刷新完成以后，headerview固定的时间
        refreshView.setPinnedTime(1000);
        refreshView.setPullLoadEnable(true);
        refreshView.setMoveForHorizontal(true);
        refreshView.setAutoLoadMore(true);
        refreshView.setEmptyView(R.layout.layout_emptyview);
        refreshView.getEmptyView().setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                refreshView.startRefresh();
            }
        });

        refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener()
        {

            @Override
            public void onRefresh()
            {
                requestData();
            }

            @Override
            public void onLoadMore(boolean isSilence)
            {
                moreData();
            }
        });

    }

    public void requestData()
    {
        initCompanyList(true,""+1,typeid);
    }

    public void moreData()
    {
        initCompanyList(false,""+page1,typeid);
    }


    private void initViewPage()
    {
        mInflater = LayoutInflater.from(this);
        expandTabView1 = (ExpandTabView) findViewById(R.id.expandtab_view);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if (item.getItemId() == android.R.id.home)
        {
            finish();
            return true ;
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_notbtn, menu);
//        MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
//        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
//        {
//            public boolean onQueryTextSubmit(String query)
//            {
//                Log.e("tag",query);
//                Intent intent=new Intent(CompanyActivity.this,SearchActivity.class);  //方法1
//                Bundle bundle=new Bundle();
//                String[] languages=getResources().getStringArray(R.array.search_array);
//
//                bundle.putString(SearchActivity.TAG_ITEM,languages[0]);
//                bundle.putString(SearchActivity.TAG_KEY, query);
//                intent.putExtras(bundle);
//                startActivity(intent);
//                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
//
//                return true;
//            }
//
//            public boolean onQueryTextChange(String newText)
//            {
//                return true;
//            }
//        });
//
//        MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener()
//        {
//            //设置打开关闭动作监听
//            @Override
//            public boolean onMenuItemActionExpand(MenuItem item)
//            {
//                return true;
//            }
//
//            @Override
//            public boolean onMenuItemActionCollapse(MenuItem item)
//            {
//                return true;
//            }
//        });
        return super.onCreateOptionsMenu(menu);
    }

    private ExpandTabView expandTabView1;

    private ArrayList<View> mViewArray1;

    private ViewLeft viewLeft;
    private ViewMiddle viewMiddle;
//    private ViewLeft viewRight;

    /**
     *
     * @param type 1为第一页 2为第二页
     * @param positionses
     * @param cities
     */
    private void initExpandView(int type,List<Positions> positionses,List<City> cities)
    {
            viewLeft = new ViewLeft(this, positionses);
            viewMiddle = new ViewMiddle(this, cities);
//            viewRight = new ViewLeft(this);
    }

    /**
     *
     * @param type 1为第一页 2为第二页
     */
    private void initExpandVaule(int type)
    {
        mViewArray1 = new ArrayList<View>();
        mViewArray1.add(viewLeft);
        mViewArray1.add(viewMiddle);
        ArrayList<String> mTextArray = new ArrayList<String>();
        mTextArray.add("类型");
        mTextArray.add("地区");
        expandTabView1.setValue(mTextArray, mViewArray1);
    }

    /**
     *
     * @param type 1为第一页 2为第二页
     */
    private void initExpandListener(int type)
    {
            viewLeft.setOnSelectListener(new ViewLeft.OnSelectListener()
            {
                @Override
                public void getValue(String distance, String showText)
                {
                    onRefresh(expandTabView1,viewLeft, showText);
                }

                @Override
                public void getValue(Positions positions, String showText)
                {
                    if (positions != null)
                    {
                        position1 = positions.id;
                    }
                }
            });

            viewMiddle.setOnSelectListener(new ViewMiddle.OnSelectListener()
            {

                @Override
                public void getValue(String showText)
                {
                    onRefresh(expandTabView1,viewMiddle, showText);
                }

                @Override
                public void getValue(City.Son son)
                {
                    if (son != null)
                    {
                        city1 = son.id;
                    }
                }
            });
    }

    private void onRefresh(ExpandTabView expandTabView,View view, String showText)
    {
        expandTabView.onPressBack();
        int position = getPositon(expandTabView,view);
        if (position >= 0 && !expandTabView.getTitle(position).equals(showText))
        {
            expandTabView.setTitle(showText, position);
        }
    }

    private int getPositon(ExpandTabView expandTabView,View tView)
    {
            for (int i = 0; i < mViewArray1.size(); i++) {
                if (mViewArray1.get(i) == tView) {
                    return i;
                }
            }
        return -1;
    }



    private void initExpandVaule()
    {
            if (expandTabView1!=null)
            {
                expandTabView1.removeAllViews();
            }
            mViewArray1 = new ArrayList<View>();
            mViewArray1.add(viewLeft);
//                    mViewArray1.add(viewRight);
            mViewArray1.add(viewMiddle);
            ArrayList<String> mTextArray = new ArrayList<String>();
            mTextArray.add("类型");
//                    mTextArray.add("价格");
            mTextArray.add("地区");
            expandTabView1.setValue(mTextArray, mViewArray1);
    }



}
